class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def closestValue(self, root, target):
        """
        :type root: TreeNode
        :type target: float
        :rtype: int
        """
        value = root.val
        while root:
            if root.val == target:
                return root.val
            if abs(root.val - target) < abs(value - target):
                value = root.val
            if target > root.val:
                root = root.right
            else:
                root = root.left
        return value